package com.qingge.springboot.controller;

import cn.hutool.json.JSONObject;
import com.qingge.springboot.common.Result;
import com.qingge.springboot.entity.PaperScore;
import com.qingge.springboot.entity.Test;
import com.qingge.springboot.service.IPaperScoreService;
import com.qingge.springboot.service.IPaperTestService;
import com.qingge.springboot.service.ITestService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@RestController
@RequestMapping("/paperScore")
public class PaperScoreController {

    @Resource
    private IPaperTestService paperTestService;

    @Resource
    private ITestService testService;

    @Resource
    private IPaperScoreService scoreService;

    @Resource
    private RedisTemplate redisTemplate;

    @PostMapping("/saveTest/{paperId}/{StuNo}")
    public Result savePaperTest(@RequestBody List<HashMap<String,String>> list, @PathVariable Integer StuNo, @PathVariable Integer paperId){
        AtomicReference<Double> score = new AtomicReference<>(0.00);
        list.stream().forEach(item->{
            //查询试题信息
            String answer = item.get("answer");
            String id = item.get("id");
            //根据试题id查询试题信息
            Test test = testService.getBaseMapper().selectById(id);
            if(test.getAnswer().equals(answer)){
                //答案正确
                double v =  2.00;
                score.updateAndGet(v1 -> v1 + v);
            }
        });
        //添加试题记录
        PaperScore paperScore = new PaperScore(null,paperId, StuNo,score.get());
        scoreService.save(paperScore);
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("score",  score );
        return Result.success(jsonObject);
    }


    @GetMapping("/expire/{paperId}")
    public Result getExpire(@PathVariable String paperId){
        Long expire = redisTemplate.getExpire(paperId);
        return Result.success(expire);
    }
}
